package org.share.comm.os;

import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URLDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 程序项目相关属性获取
 * @author hhm
 *
 */
public class ProgramUtils {
	private static final Logger _logger = LoggerFactory.getLogger(ProgramUtils.class);
	
	/**
	 * 从当前jar包所在目录
	 * 
	 * @return
	 */
	public static String getJarDir() {
		String dir = null;
		String p = new ProgramUtils().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		if (p.endsWith(".jar")) {
			p = p.substring(0, p.lastIndexOf("/"));
			dir = convertUrlByOS(p);
		}else{
			
			dir = convertUrlByOS(p);
			
			return dir;
		}
		
		try {
			//解决中文问题
			dir = URLDecoder.decode(dir, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		_logger.debug("jar directory : "+dir);
		return dir;
	}
	/**
	 * 转换通过class获取文件路径时，windows系统的路径问题
	 * 
	 * @param path
	 * @return
	 */
	private static String convertUrlByOS(String path) {
		String os = System.getProperty("os.name");
		if (os != null && os.indexOf("Windows") != -1) {
			// windows系统是去掉第一个字符 eg:/C:/dir/file.txt
			path = path.substring(1);
		}

		return path;
	}
	
	/**
	 * 获取当前程序的进程号
	 * @return
	 */
	public static int getPid(){
		RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
		String name = runtime.getName();
		int index = name.indexOf("@");
		String pid = name.substring(0, index);
		
		return Integer.parseInt(pid);
	}
	
	public static void main(String[] args) {
		ProgramUtils.getJarDir();
	}

}
